package com.itheima.service.Impl;

import com.itheima.dao.Impl.UserDao;
import com.itheima.dao.Impl.UserDaoImpl;
import com.itheima.dao.RoleDao;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.UserService;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    private RoleDao roleDao;

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<User> list() {
        List<User> userList=userDao.findAll();
       for(User user:userList){
           //遍历List集合，获取List集合中每个user对象的id
           Long id=user.getId();
           //通过id查找roleId 然后通过roleId查找Role对象集合
           List<Role> roles=roleDao.findRoleByUserId(id);
           user.setRoles(roles);
       }
        return userList;
    }

    public void save(User user, Long[] roleIds) {
        //第一步，向sys_user表中存储数据
        Long userId=userDao.save(user);
        //第二步，向sys_user_role 关系表中存储多条数据
        userDao.saveUserRoleRel(userId,roleIds);
    }

    public void del(Long userId) {
        //1.删除  sys_user_role关系表
        userDao.delUserRoleRel(userId);
        //2.删除 sys_user表
        userDao.del(userId);
    }
}
